package mr.zhang.controller;


import mr.zhang.pojo.CoderBean;
import mr.zhang.pojo.UserBean;
import mr.zhang.pojo.model.*;
import mr.zhang.service.AdminService;
import mr.zhang.service.CustomerService;
import mr.zhang.service.ProjectManagerService;
import mr.zhang.utils.CoderUtil;
import mr.zhang.utils.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * Created by jerry on 15/1/28.
 * E-mail:huaxinxc@me.com
 */
@Controller
@RequestMapping(value = "/manager/*")
public class SystemManagerController {



    private Logger log = LoggerFactory.getLogger(SystemManagerController.class);

    @Resource
    @Autowired
    private CustomerService customerService;

    @Resource
    @Autowired
    private AdminService adminService;

    @Resource
    @Autowired
    private ProjectManagerService projectManagerService;



    /**
     * 管理员登陆验证
     * @param username
     * @param password
     * @param imgCode
     * @return
     */
    @Token (remove = true)
    @RequestMapping(value = "/admin_login" )
    public String adminLoginCheck(UserBean userBean,String username , String password,
                                  String imgCode,HttpServletRequest request){
        log.info(" do login check ");

        System.out.print("登陆中输出 ：\t" + userBean.getUsername());
        request.setAttribute("user", "zhang");

        return "admin/manager";
    }

    @Token(save = true)
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public @ResponseBody Map<String ,String> JSONLoginCheck( UserBean userBean,
                                              HttpServletRequest request ,
                                              HttpServletResponse response ,HttpSession session) throws IOException{
        Map<String,String> map=new HashMap<String, String>(1);
        String username = userBean.getUsername();
        log.info("json 登陆验证");
        System.out.println("执行到这里！ " + username + userBean.getPassword());
        if(username.equals("admin")){

            map.put("success", "true");
        } else {

            map.put("error", "false");
        }

        log.info(map.toString());

        session.setAttribute("user",userBean);
        return map;

    }

    /**
     *  获取执行总监 页面数据
     * @return
     */
    @RequestMapping(value = "/manager")
    public String getViewManager(HttpSession session){

        log.info("登陆成功 获取管理员 后台信息");
        if(session != null){

        }

        // do get manager page info
        return "admin/manager";
    }

    /**
     *  管理员公共操作  重置员工权限识别码
     */
    @RequestMapping(value = "/restCoder" )
    public @ResponseBody Map<String,String> restCoder(HttpServletRequest request){
        Map<String,String> map = new HashMap<String, String>();



        CoderUtil coderUtil = new CoderUtil();

         String coder = coderUtil.getCoder();
        CoderBean coderBean = new CoderBean();
        coderBean.setKey("1");
        coderBean.setContext(coder);

        // do  insert database
        log.info("重置权限识别码" + coder);
        map.put("coder",coder);


        request.setAttribute("coderBean" ,coder);
        return map;
    }

    /**
     *
     *
     * ================== 客户信息分割线=====================
     *
     */

    /**
     * 获取客户信息列表
     * @return
     */
    @RequestMapping(value = "/getCustomer")
    public ModelAndView getCustomerList(){

        log.info("get customer list action ");

        List<TCustomer> list = new ArrayList<TCustomer>();
        list = customerService.getCustomerList();


        ModelAndView modelAndView = new ModelAndView("admin/admin_customer_view");
        modelAndView.addObject("customerList",list);

        return modelAndView;
    }

    /** 添加用户准备页面（如需提取添加用户的各项数据）
     *  add customer model
     * @return
     */
    @RequestMapping(value = "/addCustomer" )
    public String addCustomer(TCustomer customer){

        log.info("管理员 添加 用户");
        return "admin/admin_customer_add";
    }

    /**
     *  提交用户的信息到数据库 （存储）
     * @param customer
     * @return
     */
    @Token (save = true)
    @RequestMapping(value = "/addCustomerInfo" , method = RequestMethod.POST)
    public String addCustomerInfo(TCustomer customer){

        log.info("add customer to database " + customer.getCustomerName());

        customerService.addCustomer(customer);

        return "redirect:/app/manager/getCustomer";
    }




    /**
     *
     *
     * ================== 员工控制分割线=====================
     *
     */

    /**员工控制列表
     *
     * @return url
     */
    @RequestMapping(value = "/getEmployee")
    public String getEmployeeList(){
        log.info("员工列表");
        return "admin/admin_employee_view";
    }

    /**
     *  添加员工
     *  @param
     * @return
     */
    @RequestMapping(value = "/addEmployee")
    public String addEmployee(){

        return "admin/admin_employee_add";
    }





    /**
     *
     *
     * ================== 项目管理控制器群=====================
     *
     */

    /**
     *  返回项目列表
     * @return
     */
    @RequestMapping(value = "/getPoject")
    public ModelAndView getPojectController(){

        List<TCensusProject> pojectList = projectManagerService.getProjectList();
        log.info("PojectList size:\t"+pojectList.size());
        ModelAndView modelAndView = new ModelAndView("admin/admin_poject_view");
        modelAndView.addObject("pojectList" , pojectList);

        return modelAndView;
    }


    /**
     * 添加项目显示界面
     * @return
     */
    @RequestMapping(value = "/addPojectView")
    public ModelAndView addPojectView(){

        TProject tProject = new TProject();

        String consultantCoder = CoderUtil.getCoder();
        String backCoder = CoderUtil.getCoder();
        String managerCoder = CoderUtil.getCoder();
        String caseCoder = CoderUtil.getCoder();

        ModelAndView modelAndView = new ModelAndView("admin/admin_poject_add");
        modelAndView.addObject("pojectList" ,tProject);

        modelAndView.addObject("backCoder",backCoder);
        modelAndView.addObject("consultantCoder",consultantCoder);
        modelAndView.addObject("managerCoder",managerCoder);
        modelAndView.addObject("caseCoder",caseCoder);
        return modelAndView;

    }

    /**
     * 执行项目添加
     * @param tProject
     * @return
     */
    @RequestMapping(value ="/addPoject" , method = RequestMethod.POST)
    @Token (save = true)
    public ModelAndView addPojectCheck(@ModelAttribute("tPoject")
                                           @Valid TProject tProject , BindingResult result, Model model,HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        TSalesDirector sale = new TSalesDirector();
        String  consultantCoder = request.getParameter("consultantCoder");
        String managerCoder = request.getParameter("managerCoder");

        System.out.println("传递过来到 coder ＋ \t" + consultantCoder + "\t" + managerCoder);

        if(!result.hasErrors()){
            System.out.println("success");

            //将销售经理的 属性封装进 project
            TSalesDirector tSalesDirector = new TSalesDirector();
            tSalesDirector.setVerification_code(consultantCoder);

            tProject.setTSalesDirector(tSalesDirector);


            Set<TTeam> team = new HashSet<TTeam>();
            team = tProject.getTTeams();

            team.addAll(team);
            tProject.setTTeams(team);


            log.info("pring name " + "\t" + team);
            System.out.println("do it !" + team.toString());

        }

        boolean flag = projectManagerService.addProject(tProject);

        System.out.println("执行插入没有 ！ " + flag);

        if(flag){
            modelAndView.setViewName("redirect:/app/manager/getPoject");
        } else {
            modelAndView.setViewName("error");
        }

        return  modelAndView;
    }



    @RequestMapping(value = "/editPoject")
    public ModelAndView editPoject(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView("admin/admin_poject_edit");

        String id =  request.getParameter("id");
        modelAndView.addObject("id",id);
        // do database ..

        modelAndView.setViewName("redirect:/app/manager/getPoject");
        return modelAndView;
    }


    /**
     *
     *
     * ================== 财务信息分割线=====================
     *
     */

    /**
     *  财务报表控制器
     * @return url
     */
    @RequestMapping(value = "/getFinance")
    public String getFinanceList(){

        log.info("财务报表");

        return "admin/admin_finance_view";
    }






}
